﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CommHelper
{
    public static class ConvertHelper
    {
        private static int decimalReport = CommHelper.AppSettingsHelper.GetInt("DecimalPlacesReport");
        private static int decimalPlaces = CommHelper.AppSettingsHelper.GetInt("DecimalPlacesPrice");
        /// <summary>
        /// 将字节数组转化为字符串
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static string BytesToString(byte[] bytes)
        {
            if (bytes == null) return null;
            StringBuilder sb = new StringBuilder();
            foreach (byte b in bytes)
            {
                sb.AppendFormat("{0:X2}", b);
            }
            return sb.ToString();
        }

        /// <summary>
        /// 将字符串转化为字节数组,适用与本程序环境
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static byte[] StringToBytes(string str)
        {
            if (string.IsNullOrEmpty(str)) return null;
            int len = str.Length / 2;
            byte[] ret = new byte[len];
            for (int i = 0; i < len; i++)
            {
                ret[i] = (byte)Convert.ToInt32(str.Substring(i * 2, 2), 16);
            }
            return ret;
        }

        /// <summary>
        /// model中这样的int?类型很烦，转换下
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static int IntNullToInt(int? value)
        {
            if (value == null) return 0;
            else
                return value.Value;
        }

        /// <summary>
        /// long? 转换为 long
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static long Int64NullToLong(long? value)
        {
            if (value == null)
                return 0;
            else
                return value.Value;
        }

        /// <summary>
        /// model中这样的decimal?类型很烦，转换下
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static decimal DecimalNullToDecimal(decimal? value)
        {
            if (value == null) return 0;
            else
                return value.Value;
        }

        /// <summary>
        /// 将 DateTime ? 转换为 DateTime
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static DateTime DateTimeNullToDateTime(DateTime? value)
        {
            if (value == null)
                return DateTime.MinValue;
            else
                return value.Value;
        }

        /// <summary>
        /// 获取图片框的字节流
        /// </summary>
        /// <param name="pb">图片框</param>
        /// <returns></returns>
        public static byte[] GetBytesByImage(System.Windows.Forms.PictureBox pb)
        {
            byte[] photo_byte = null;
            if (pb == null || pb.Image == null) return null;
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(pb.Image);
                bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                photo_byte = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(photo_byte, 0, Convert.ToInt32(ms.Length));
                bmp.Dispose();
            }
            return photo_byte;
        }

        /// <summary>
        /// 获取图片框的字符串数据
        /// </summary>
        /// <param name="pb">图片框</param>
        /// <returns></returns>
        public static string GetStringByImage(System.Windows.Forms.PictureBox pb)
        {
            return BytesToString(GetBytesByImage(pb));
        }

        /// <summary>
        /// 字节流转变为图片
        /// </summary>
        /// <param name="bytes">字节流</param>
        /// <returns></returns>
        public static System.Drawing.Image GetImageByBytes(byte[] bytes)
        {
            if (bytes == null) return null;
            System.Drawing.Image photo = null;
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream(bytes))
            {
                ms.Write(bytes, 0, bytes.Length);
                photo = System.Drawing.Image.FromStream(ms, true);
            }

            return photo;
        }

        /// <summary>
        /// 字符串转变为图片
        /// </summary>
        /// <param name="strPic">字符串图片数据</param>
        /// <returns></returns>
        public static System.Drawing.Image GetImageByString(string strPic)
        {
            return GetImageByBytes(StringToBytes(strPic));
        }

        /// <summary>
        /// 按系统配置精确到小数点后几位（价格）
        /// </summary>
        /// <param name="decimalValue"></param>
        /// <returns></returns>
        public static decimal ConventDecimalPlacesPrice(this decimal decimalValue)
        {
            return ConventDecimalPlaces(decimalValue, decimalPlaces);
        }

        /// <summary>
        /// 按系统配置精确到小数点后几位（报表）
        /// </summary>
        /// <param name="decimalValue"></param>
        /// <returns></returns>
        public static decimal ConventDecimalPlacesReport(this decimal decimalValue)
        {
            return ConventDecimalPlaces(decimalValue, decimalReport);
        }

        /// <summary>
        /// 按系统配置精确到小数点后几位（价格）
        /// </summary>
        /// <param name="decimalValue"></param>
        /// <param name="withMark">是否带￥</param>
        /// <returns></returns>
        public static string ConventDecimalToStringPrice(this decimal decimalValue, bool withMark = false)
        {
            var value = ConventDecimalPlaces(decimalValue, decimalPlaces);
            if (withMark)
                return "￥" + value;
            else
                return value + "";
        }

        /// <summary>
        /// 按系统配置精确到小数点后几位（报表）
        /// </summary>
        /// <param name="decimalValue"></param>
        /// <param name="withMark">是否带￥</param>
        /// <returns></returns>
        public static string ConventDecimalToStringReport(this decimal decimalValue, bool withMark = false)
        {
            var value = ConventDecimalPlaces(decimalValue, decimalReport);
            if (withMark)
                return "￥" + value;
            else
                return value + "";
        }

        /// <summary>
        /// 精确到小数点后几位
        /// </summary>
        /// <param name="decimalvalue"></param>
        /// <param name="decimalSpace"></param>
        /// <returns></returns>
        public static decimal ConventDecimalPlaces(decimal decimalvalue, int decimalPlaces)
        {
            if (decimalPlaces < 0) decimalPlaces = 0;
            if (decimalPlaces==0)return Math.Truncate(decimalvalue);
            decimal value = (decimal)Math.Pow(10, decimalPlaces);
             
            return Math.Truncate(decimalvalue * value) / value; 
        }
        /// <summary>
        /// 根据订单号获取当天流水号
        /// </summary>
        /// <returns></returns>
        public static string Serialnumber(Int64 orderid)
        {
            string orderstr = orderid.ToString();
            if (orderstr.Length > 14)
            {
                orderstr = orderstr.Substring(14);
            }
            return string.Format("#{0}", orderstr);
        }

        /// <summary>
        /// 将用‘，’分割的ID字符串转变为不重复的int列表
        /// </summary>
        /// <param name="text">转换的字符串</param>
        /// <returns></returns>
        public static List<int> ConventStringToListInt(string text)
        {
            List<int> listint = new List<int>();
            string[] idstrings = text.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            if (idstrings != null)
            {
                int id = 0;
                foreach (var item in idstrings)
                {
                    if (int.TryParse(item, out id))
                    {
                        if (!listint.Contains(id))
                        {
                            listint.Add(id);
                        }
                    }
                }
            }
            return listint;
        }

        /// <summary>
        /// 比较两个字符串是否相同
        /// 默认null和空是相等的
        /// </summary>
        /// <param name="strFrom"></param>
        /// <param name="strTo"></param>
        /// <returns></returns>
        public static bool CompareString(string strFrom, string strTo)
        {
            if (string.IsNullOrEmpty(strFrom) && string.IsNullOrEmpty(strTo))
                return true;
            else if (string.IsNullOrEmpty(strFrom) || string.IsNullOrEmpty(strTo))
                return false;
            else
                return strFrom == strTo;
        }

        /// <summary>
        /// 将文本转变为语音流
        /// </summary>
        /// <param name="words">文本</param>
        /// <returns></returns>
        public static byte[] ConventStringToSpeakByte(string words)
        {
            try
            {
                using (System.Speech.Synthesis.SpeechSynthesizer tts = new System.Speech.Synthesis.SpeechSynthesizer())
                {
                    var stream = new System.IO.MemoryStream();
                    tts.SetOutputToWaveStream(stream);
                    tts.Speak(words);
                    return stream.ToArray();
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteWarningLog(ex.Message);
            }
            return null;
        }
    }
}
